﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.Diagnostics;

namespace ADSync2
{
	static class Program
	{
		/// <summary>
		/// The main entry point for the application.
		/// </summary>
        static void Main(string[] args)
        {
            try
            {
                HashSet<string> validParameters = new HashSet<string>(StringComparer.OrdinalIgnoreCase){"-k", "-u"};
                //make sure appsettings can be initiated - only windows service is set
                NameValueCollection currentAppConfiguration = ConfigurationManager.AppSettings;

                if (args.Length > 0 && args.Length % 2 == 0)
                {
					try
					{
						ConfigurationComponent.EngineConfiguration engineConfigurationInstance = new ConfigurationComponent.EngineConfiguration(ConfigurationManager.AppSettings);

						for (int i = 0; i < args.Length; i += 2)
						{
							if (validParameters.Contains(args[i]))
							{
								if (args[i].Equals("-k", StringComparison.OrdinalIgnoreCase))
								{
									string groupBaseDn = String.Empty;
									if (engineConfigurationInstance.KeyValue.ContainsKey("GROUP_BASEDN"))
									{
										groupBaseDn = engineConfigurationInstance.KeyValue["GROUP_BASEDN"];
									}
									engineConfigurationInstance.KeyValue["GROUP_BASEDN"] = String.Format("OU={0},{1}", args[i + 1], groupBaseDn);
								}
								else if (args[i].Equals("-u", StringComparison.OrdinalIgnoreCase))
								{
									string userFilter = String.Empty;
									if (engineConfigurationInstance.KeyValue.ContainsKey("USER_FILTER"))
									{
										userFilter = engineConfigurationInstance.KeyValue["USER_FILTER"];
									}
									engineConfigurationInstance.KeyValue["USER_FILTER"] = String.Format("(&(|(sAMAccountName={0})(cn={0})){1})", args[i + 1], userFilter);
								}
								engineConfigurationInstance.KeyValue["SYNC_TYPE"] = "FULL_SYNC";
								engineConfigurationInstance.KeyValue["LOG"] = "VERBOSE:CLI";
							}
							else
							{
								Message();
							}
						}
						using (Engine EngineObject = new Engine(engineConfigurationInstance))
						{
							System.Reflection.Assembly objAssembly = System.Reflection.Assembly.GetExecutingAssembly();

							Console.WriteLine(String.Empty);
							Console.WriteLine("------------------------------------------------------------");
							Console.WriteLine("------------------------------------------------------------");
							Console.WriteLine( ((System.Reflection.AssemblyDescriptionAttribute)System.Reflection.AssemblyDescriptionAttribute.GetCustomAttribute(objAssembly, typeof(System.Reflection.AssemblyDescriptionAttribute))).Description);
							Console.WriteLine( ((System.Reflection.AssemblyCompanyAttribute)System.Reflection.AssemblyCompanyAttribute.GetCustomAttribute(objAssembly, typeof(System.Reflection.AssemblyCompanyAttribute))).Company );
							Console.WriteLine( ((System.Reflection.AssemblyCopyrightAttribute)System.Reflection.AssemblyCopyrightAttribute.GetCustomAttribute(objAssembly, typeof(System.Reflection.AssemblyCopyrightAttribute))).Copyright );
							Console.WriteLine("------------------------------------------------------------");
							Console.WriteLine("------------------------------------------------------------");
							Console.WriteLine(String.Format("Synchronization Type: {0}", engineConfigurationInstance.KeyValue["SYNC_TYPE"]));
							Console.WriteLine(String.Format("Running Mode: {0}", engineConfigurationInstance.KeyValue["MODE"]));
							Console.WriteLine(String.Format("User filter: {0}", engineConfigurationInstance.KeyValue["USER_FILTER"]));
							Console.WriteLine(String.Format("Group Search Root DN: {0}", engineConfigurationInstance.KeyValue["GROUP_BASEDN"]));
							Console.WriteLine(String.Empty);
							Console.WriteLine("Synchronizing (may take up to several minutes)..");
							Console.WriteLine("------------------------------------------------------------");

							EngineObject.Start();
						}
					}
					catch (Exception eX)
					{
						Console.WriteLine(String.Format("{0}::{1}", new StackFrame(0, true).GetMethod().Name, eX.Message));
					}
                }
                else
                {
                    Message();
                }
            }
            catch(Exception eX)
            {
                Console.WriteLine(eX.Message);
            }
		}
        private static void Message()
        {
            Console.WriteLine(String.Format(@"
Syntax error!

Syntax:
{0} [-k <KG Name>]
    [-u <user sAMAccountName>]

Examples:
{0} -k INF -u spyragr
	Executes sync operation against 'spyragr' account for all groups provisioned into INF OU
	(check GROUP_BASEDN in configuration file for further details regarding SearchRoot OU).
",
               System.AppDomain.CurrentDomain.FriendlyName)
 );
        }
	}
}
